import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:my_salary/pages/timeline/timeline_vm.dart';
import 'package:timelines_plus/timelines_plus.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class TimelinePage extends StatefulWidget {
  const TimelinePage({super.key});

  @override
  State<TimelinePage> createState() => _TimelinePageState();
}

class _TimelinePageState extends State<TimelinePage>
    with WidgetsBindingObserver {
  final TimelineViewModel _viewModel = TimelineViewModel();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final cs = Theme.of(context).colorScheme;
    final tt = Theme.of(context).textTheme;

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.timelineTitle, style: tt.titleLarge),
        backgroundColor: cs.surface,
        elevation: 0.5,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(20.w),
          child: FixedTimeline.tileBuilder(
            theme: TimelineThemeData(
              nodePosition: 0,
              color: cs.outline,
              indicatorTheme: IndicatorThemeData(
                position: 0,
                size: 20.w,
              ),
              connectorTheme: ConnectorThemeData(
                thickness: 2.5,
                color: cs.outlineVariant,
              ),
            ),
            builder: TimelineTileBuilder.connected(
              connectionDirection: ConnectionDirection.before,
              itemCount: _viewModel.timelineData.length,
              contentsBuilder: (_, index) {
                final item = _viewModel.timelineData[index];
                if (item.isCompleted) return null;

                return Padding(
                  padding: EdgeInsets.only(left: 8.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildDateChip(context, item.time),
                      SizedBox(height: 8.h),
                      _buildContents(context, item),
                      SizedBox(height: 18.h),
                    ],
                  ),
                );
              },
              indicatorBuilder: (_, index) {
                final item = _viewModel.timelineData[index];
                return item.isCompleted
                    ? DotIndicator(
                  color: cs.primary,
                  child: Icon(Icons.check,
                      color: cs.onPrimary, size: 12.sp),
                )
                    : OutlinedDotIndicator(
                  borderWidth: 2.5,
                  color: cs.outline,
                );
              },
              connectorBuilder: (_, index, type) {
                final item = _viewModel.timelineData[index];
                return SolidLineConnector(
                  color: item.isCompleted ? cs.primary : cs.outlineVariant,
                  thickness: 2.5,
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDateChip(BuildContext context, String time) {
    final cs = Theme.of(context).colorScheme;
    final tt = Theme.of(context).textTheme;
    return TextButton.icon(
      onPressed: () {},
      icon: Icon(Icons.calendar_month,
          color: cs.onSurfaceVariant, size: 18.sp),
      label: Text(
        time,
        style: tt.bodyMedium?.copyWith(color: cs.onSurface, fontSize: 16.sp),
      ),
      style: TextButton.styleFrom(
        side: BorderSide(color: cs.outline, width: 1.5),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.r)),
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
      ),
    );
  }
}

class _OnTimeBar extends StatelessWidget {
  const _OnTimeBar();

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final cs = Theme.of(context).colorScheme;
    return Row(
      children: [
        FilledButton(
          onPressed: () {
            ScaffoldMessenger.of(context).showSnackBar(
               SnackBar(content: Text(l10n.commonConfirm)),
            );
          },
          style: FilledButton.styleFrom(
            backgroundColor: cs.primary,
            foregroundColor: cs.onPrimary,
            shape: const StadiumBorder(),
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          ),
          child:  Text(l10n.commonConfirm),
        ),
        const Spacer(),
        FilledButton.tonal(
          onPressed: () {},
          style: FilledButton.styleFrom(
            shape: const StadiumBorder(),
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          ),
          child: Text(l10n.timelineMoreDetails),
        ),
      ],
    );
  }
}

Widget _buildContents(BuildContext context, TimelineItem item) {
  final l10n = AppLocalizations.of(context)!;
  final tt = Theme.of(context).textTheme;
  // TODO: 本月交易数
  return Card(
    elevation: 2,
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.r)),
    child: Padding(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(item.title,
              style: tt.titleMedium?.copyWith(fontWeight: FontWeight.bold)),
          ExpansionTile(
            tilePadding: EdgeInsets.zero,
            title: Text(
              '${l10n.timelineMonthlyTransactions(7)}',
              style: tt.bodySmall,
            ),
            children: [
              _InnerTimeline(messages: item.events),
            ],
          ),
          const _OnTimeBar(),
        ],
      ),
    ),
  );
}

class _InnerTimeline extends StatelessWidget {
  const _InnerTimeline({required this.messages});
  final List<TimelineEvent> messages;

  bool isEdgeIndex(int index) =>
      index == 0 || index == messages.length + 1;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 2.h),
      child: FixedTimeline.tileBuilder(
        theme: TimelineTheme.of(context).copyWith(
          nodePosition: 0,
          connectorTheme: TimelineTheme.of(context)
              .connectorTheme
              .copyWith(thickness: 1.0),
          indicatorTheme: TimelineTheme.of(context)
              .indicatorTheme
              .copyWith(size: 10.0, position: 0.5),
        ),
        builder: TimelineTileBuilder(
          indicatorBuilder: (_, index) =>
          !isEdgeIndex(index)
              ? Indicator.outlined(borderWidth: 1.0)
              : null,
          startConnectorBuilder: (_, __) => Connector.solidLine(),
          endConnectorBuilder: (_, __) => Connector.solidLine(),
          contentsBuilder: (_, index) {
            if (isEdgeIndex(index)) return null;
            final event = messages[index - 1];
            return RichText(
              text: TextSpan(
                style: DefaultTextStyle.of(context).style,
                children: [
                  TextSpan(
                    text: event.createdAt,
                    style: Theme.of(context).textTheme.bodySmall?.copyWith(
                      color: Colors.blueGrey,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const TextSpan(text: " "),
                  TextSpan(text: event.message),
                ],
              ),
            );
          },
          itemExtentBuilder: (_, index) =>
          isEdgeIndex(index) ? 10.0 : 50.0.h,
          nodeItemOverlapBuilder: (_, index) =>
          isEdgeIndex(index) ? true : null,
          itemCount: messages.length + 2,
        ),
      ),
    );
  }
}
